package com.elvish.efast.modules.sys.controller;

import com.elvish.efast.common.anno.BuildTree;
import com.elvish.efast.common.consts.Const;
import com.elvish.efast.common.entity.Result;
import com.elvish.efast.common.entity.TreeData;
import com.elvish.efast.common.enums.ResultCode;
import com.elvish.efast.common.utils.CommonUtil;
import com.elvish.efast.common.utils.ResultUtil;
import com.elvish.efast.modules.sys.entity.Permission;
import com.elvish.efast.modules.sys.service.PermissionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

/**
 * (TPermission)表控制层
 *
 * @author makejava
 * @since 2018-11-19 14:22:46
 */
@RestController
@RequestMapping("/permission")
@Slf4j
public class PermissionController {
    /**
     * 服务对象
     */
    @Resource
    private PermissionService tPermissionService;

    /**
     * 查询菜单列表
     *
     * @return 响应消息
     */
    @GetMapping("/queryAll")
    public Result queryAll(Permission permission) {
        return ResultUtil.success(tPermissionService.queryAll(permission));
    }

    /**
     * 查询所有权限
     *
     * @return 所有权限数据
     */
    @GetMapping("/getTreeData")
    @BuildTree
    public List<TreeData> getTreeData() {
        return tPermissionService.getTreeData();
    }

    /**
     * 查询权限列表
     *
     * @return 所有权限数据
     */
    @GetMapping("/getAuthTree")
    public List<Permission> getAuthTree(String roleId) {
        return this.tPermissionService.getAuthTree(roleId);
    }

    /**
     * 操作菜单
     *
     * @param oper 操作符
     * @param menu 菜单对象
     * @return 响应消息
     */
    @PostMapping("/editPermission")
    public Result editPermission(int oper, @RequestBody Permission permission) {
        Result result = null;
        try {
            if (oper == Const.OperationType.ADD) {
                permission.setId(CommonUtil.uuid());
                this.tPermissionService.insert(permission);
            } else if (oper == Const.OperationType.UPDATE) {
                this.tPermissionService.update(permission);
            } else if (oper == Const.OperationType.DELETE) {
                this.tPermissionService.deleteById(permission);
            }
            result = ResultUtil.success();
        } catch (Exception e) {
            log.error("editMenu error", e);
            result = ResultUtil.fail(ResultCode.ERROR);
        }
        return result;
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("selectOne")
    public Permission selectOne(String id) {
        return this.tPermissionService.queryById(id);
    }

}